//
//  MusicPlyController.m
//  艾听歌
//
//  Created by dllo on 16/5/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "MusicPlyController.h"
#import "UrlListModel.h"
#import "STKAudioPlayer.h"

@interface MusicPlyController ()<STKAudioPlayerDelegate,UMSocialUIDelegate>

@property (nonatomic , strong) STKAudioPlayer *myAudioPlayer;
@property (nonatomic , assign) NSInteger song_id;//传过来的音频id
@property (nonatomic , strong) NSTimer *timer;
@property (nonatomic , strong) NSMutableArray *allMusicArray;//存放上一页列表所有数据
@property (nonatomic , assign) NSInteger indexRow;//记录上一页点击cell的下标
@property (nonatomic , strong) UIButton *playButton;
@property (nonatomic , strong) UIButton *NextButton;
@property (nonatomic , assign) NSInteger songId;
@property (nonatomic , strong) UISlider *progressSlider;
@property (nonatomic , strong) UILabel *timerLabel;
@property (nonatomic , strong) UISlider *volumeSlider;

@property (nonatomic , strong)  UILabel *currTimeLabel;
@property (nonatomic , strong)  UILabel *totalTimeLabel;
@property (nonatomic , strong) UIImageView *BackImage;
@property (nonatomic , strong) UIView *bottomView;
@property (nonatomic , strong) UIButton *shareButton;
@property (nonatomic , copy)  NSString *shareNsstring;
@end

@implementation MusicPlyController
// 播放单例  只能播放一首歌
+(MusicPlyController *)musicplyVC{
    static MusicPlyController *music = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        music = [[MusicPlyController alloc]init];
        
    });
    
    return music;
}
// 将传过来的音乐播放存起来
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSUserDefaults standardUserDefaults] setObject:self.MusicArray forKey:@"playing"];
    

    NSLog(@"%ld",self.index);
    if (self.index != self.indexRow) {

        [self PlayMusic];
        self.indexRow = self.index;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = [UIColor blackColor];
    self.view.alpha = 0.3;
    self.indexRow = -1;
    
    self.BackImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    [self.view addSubview:self.BackImage];
    self.BackImage.backgroundColor = [UIColor blueColor];
    
    self.BackImage.image = [UIImage imageNamed:@"lyric-sharing-background-1"];
    
    [self createBottomView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor whiteColor];
    button.frame = CGRectMake(20, 30, 20, 20);
    [self.view addSubview:button];
    [button setBackgroundImage:[UIImage imageNamed:@"btn_back"] forState:(UIControlStateNormal)];
        [self.navigationController.navigationBar addSubview:button];
    [button addTarget:self action:@selector(ModelAction) forControlEvents:UIControlEventTouchUpInside];
    

    
    
//    self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    //    shareButton.backgroundColor = [UIColor whiteColor];
//    self.shareButton.frame = CGRectMake(235, 500, 30, 30);
//    [self.view addSubview:self.shareButton];
//    [self.shareButton setBackgroundImage:[UIImage imageNamed:@"Unknown"] forState:(UIControlStateNormal)];
//    self.shareButton.tintColor = [UIColor whiteColor];
//    [self.shareButton addTarget:self action:@selector(shareButton1) forControlEvents:UIControlEventTouchUpInside];
    
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(80, 565, WIDTH - 80 - 80, 10)];
    [self.progressSlider addTarget:self action:@selector(progressSlider:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.progressSlider];
    
    self.currTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 565 - 25, 60, 60)];
    self.currTimeLabel.backgroundColor = [UIColor clearColor];
    self.currTimeLabel.font = [UIFont systemFontOfSize:17];
    self.currTimeLabel.textColor = [UIColor whiteColor];
    self.currTimeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.currTimeLabel];
    
    
    self.totalTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH - 10 - 60, 565 - 25, 60, 60)];
    self.totalTimeLabel.backgroundColor = [UIColor clearColor];
    self.totalTimeLabel.font = [UIFont systemFontOfSize:17];
    self.totalTimeLabel.textColor = [UIColor whiteColor];
    self.totalTimeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.totalTimeLabel];
    
    
    UIButton *UpButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UpButton.frame = CGRectMake(80, 610, 40, 40);
    [self.view addSubview:UpButton];
    UpButton.backgroundColor = [UIColor clearColor];
    [UpButton addTarget:self action:@selector(UpButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [UpButton setBackgroundImage:[UIImage imageNamed:@"player_btn_pre_normal"] forState:(UIControlStateNormal)];
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playButton.frame = CGRectMake(175, 610, 50, 50);
    [self.view addSubview:self.playButton];
    [self.playButton addTarget:self action:@selector(PlayMusic) forControlEvents:UIControlEventTouchUpInside];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"player_btn_play_normal"] forState:UIControlStateNormal];
    self.playButton.backgroundColor = [UIColor clearColor];
    
    self.NextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.NextButton.frame = CGRectMake(270, 610, 40, 40);
    self.NextButton.backgroundColor = [UIColor clearColor];
    [self.NextButton addTarget:self action:@selector(NextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.NextButton setBackgroundImage:[UIImage imageNamed:@"player_btn_next_normal"] forState:(UIControlStateNormal)];
    [self.view addSubview:self.NextButton];
     
    self.myAudioPlayer = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    // 签协议
    self.myAudioPlayer.delegate = self;
    self.myAudioPlayer.volume = 0.5;
    
//    [self.myAudioPlayer play:self.MusicArray[self.index]];//
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(track) userInfo:nil repeats:YES];
   
    [self createEmitterLayer];
}

- (void)ModelAction {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)createBottomView{
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT - 270, WIDTH, 270)];
    //    self.bottomView.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.8];
    [self.bottomView.layer addSublayer:[self shadowAsInverse]];
    [self.view addSubview:self.bottomView];
}

- (CAGradientLayer *)shadowAsInverse
{
    CAGradientLayer *newShadow = [[CAGradientLayer alloc] init];
    CGRect newShadowFrame = CGRectMake(0, 0, WIDTH, 270);
    newShadow.frame = newShadowFrame;
    //添加渐变的颜色组合（颜色透明度的改变）阴影效果 
    newShadow.colors = [NSArray arrayWithObjects:(id)[[[UIColor blackColor] colorWithAlphaComponent:0.2] CGColor],(id)[[[UIColor blackColor] colorWithAlphaComponent:0.3] CGColor],(id)[[[UIColor blackColor] colorWithAlphaComponent:0.5] CGColor],(id)[[[UIColor blackColor] colorWithAlphaComponent:0.7] CGColor],(id)[[[UIColor blackColor] colorWithAlphaComponent:0.9] CGColor],(id)[[[UIColor blackColor] colorWithAlphaComponent:1] CGColor],
                        nil];
    return newShadow;
}

- (void)createEmitterLayer{
    // =================== 樱花飘落 ====================
    CAEmitterLayer * snowEmitterLayer = [CAEmitterLayer layer];
    snowEmitterLayer.emitterPosition = CGPointMake(100, -30);
    snowEmitterLayer.emitterSize = CGSizeMake(self.view.bounds.size.width * 2, 0);
    snowEmitterLayer.emitterMode = kCAEmitterLayerOutline;
    snowEmitterLayer.emitterShape = kCAEmitterLayerLine;
    //    snowEmitterLayer.renderMode = kCAEmitterLayerAdditive;
    
    CAEmitterCell * snowCell = [CAEmitterCell emitterCell];
    snowCell.contents = (__bridge id)[UIImage imageNamed:@"樱花瓣2"].CGImage;
    
    // 花瓣缩放比例
    snowCell.scale = 0.02;
    snowCell.scaleRange = 0.5;
    
    // 每秒产生的花瓣数量
    snowCell.birthRate = 100;
    snowCell.lifetime = 80;
    
    // 每秒花瓣变透明的速度
    snowCell.alphaSpeed = -0.01;
    
    // 秒速“五”厘米～～
    snowCell.velocity = 40;
    snowCell.velocityRange = 60;
    
    // 花瓣掉落的角度范围
    snowCell.emissionRange = M_PI;
    
    // 花瓣旋转的速度
    snowCell.spin = M_PI_4;
    
    // 每个cell的颜色
    //    snowCell.color = [[UIColor redColor] CGColor];
    
    // 阴影的 不透明 度
    snowEmitterLayer.shadowOpacity = 1;
    // 阴影化开的程度（就像墨水滴在宣纸上化开那样）
    snowEmitterLayer.shadowRadius = 8;
    // 阴影的偏移量
    snowEmitterLayer.shadowOffset = CGSizeMake(3, 3);
    // 阴影的颜色
    snowEmitterLayer.shadowColor = [[UIColor whiteColor] CGColor];
    
    
    snowEmitterLayer.emitterCells = [NSArray arrayWithObject:snowCell];
    [self.BackImage.layer addSublayer:snowEmitterLayer];
}
// 每秒调用一次此方法
- (void)track
{
    self.progressSlider.maximumValue = self.myAudioPlayer.duration;
    self.progressSlider.value = self.myAudioPlayer.progress;
    
    NSInteger proMin = (NSInteger)self.myAudioPlayer.progress / 60;
    NSInteger proSec = (NSInteger)self.myAudioPlayer.progress % 60;
    
    NSInteger durMin = (NSInteger)self.myAudioPlayer.duration / 60;
    NSInteger durSec = (NSInteger)self.myAudioPlayer.duration % 60;
    
//    self.timerLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld",proMin, proSec, durMin, durSec];
    
    self.currTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",proMin, proSec];
    
    self.totalTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",durMin, durSec];
}

- (void)progressSlider:(UISlider *)sender
{
    if (self.myAudioPlayer) {
        [self.myAudioPlayer seekToTime:sender.value];
    }
}

- (void)shareButton1
{
    /**
     根据平台名，返回平台对象
     
     @param platformName sns平台名
     
     @return UMSocialSnsPlatform 平台对象
     */
    
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    /**
     Sns平台类，用`platformName`作为标识，指定显示名称、显示的图片，点击之后的响应。
     */
    snsPlatform.displayName = @"新浪";
    snsPlatform.loginName = @"网易";
    
    
    UMSocialSnsPlatform *snsPlatform2 = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToTencent];
    snsPlatform2.displayName = @"腾讯微博";
    
    
    NSArray *shareArr = [NSArray arrayWithObjects:UMShareToTencent, UMShareToSina,UMShareToQzone,UMShareToRenren,nil];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.shareNsstring]]];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"574b959de0f55a11d9000582"
                                      shareText:@"你要分享的文字❤️"
                                     shareImage:image
                                shareToSnsNames:shareArr
                                       delegate:self];
}

- (void)PlayMusic
{
    if (self.myAudioPlayer.state == STKAudioPlayerStatePaused) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"player_btn_play_normal"] forState:UIControlStateNormal];
        [self.myAudioPlayer resume];// 继续
    }else if (self.myAudioPlayer.state == STKAudioPlayerStatePlaying) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"player_btn_pause_normal"] forState:UIControlStateNormal];
        [self.myAudioPlayer pause];
    }else{
        NSString *url = [self.MusicArray objectAtIndex:self.index];
        [self.myAudioPlayer play:url];
//        [self.playButton setBackgroundImage:[UIImage imageNamed:@"player_btn_pause_normal"] forState:UIControlStateNormal];
    }
}
- (void)NextButtonAction:(UIButton *)button
{
    self.indexRow = (self.indexRow + 1) % self.MusicArray.count;
    self.index = self.indexRow;
    if (self.indexRow < self.MusicArray.count) {
        NSString *url = [self.MusicArray objectAtIndex:self.indexRow];
        //[self.myAudioPlayer stop];
        [self.myAudioPlayer play:url];
    }else {
        NSString *url = [self.MusicArray objectAtIndex:self.indexRow];
        [self.myAudioPlayer play:url];
    }
}
- (void)UpButtonAction:(UIButton *)button
{
    self.indexRow = (self.indexRow - 1) % self.MusicArray.count;
    if(self.indexRow < 0) {
        self.indexRow = self.MusicArray.count + self.indexRow;
    }
    self.index = self.indexRow;
    if (self.indexRow < self.MusicArray.count) {
        NSString *url = [self.MusicArray objectAtIndex:self.indexRow];
       
        [self.myAudioPlayer play:url];
    }else {
        NSString *url = [self.MusicArray objectAtIndex:self.indexRow];
        [self.myAudioPlayer play:url];
    }
}

// 视图将要出现的时候 tabBar隐藏
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
}

#pragma mark - player代理方法
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration{
    
    if (STKAudioPlayerStopReasonEof == stopReason) {
        [self NextButtonAction:self.NextButton];
    }
    if (stopReason == 1) {
         NSString *url = [self.MusicArray objectAtIndex:self.indexRow];
        [self.myAudioPlayer play:url];
    }
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId{
    
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId{
    
}
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState{
    
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode{
    
}



@end
